package com.qdsg.ysg.doctor.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.location.Address;
import android.os.Build;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.gyf.immersionbar.ImmersionBar;
import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseActivity;
import com.qdsg.ysg.doctor.base.BaseApplication;
import com.qdsg.ysg.doctor.eventbus.Logout;
import com.qdsg.ysg.doctor.fw_permission.FloatWinPermissionCompat;
import com.qdsg.ysg.doctor.nurse.fragment.HomeNurseFragment;
import com.qdsg.ysg.doctor.pharmacist.fragment.PrescriptionFragment;
import com.qdsg.ysg.doctor.service.WebSocketService;
import com.qdsg.ysg.doctor.ui.dialog.ApplyPermissionDialog;
import com.qdsg.ysg.doctor.ui.fragment.ContactsFragment;
import com.qdsg.ysg.doctor.ui.fragment.HomeFragment;
import com.qdsg.ysg.doctor.ui.fragment.MineFragment;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.response.BaseResponse;
import com.rest.response.DocInfoVO;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LocationUtils;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.PreferencesHelper;

public class MainActivity extends BaseActivity implements BottomNavigationBar.OnTabSelectedListener {

    BottomNavigationBar bottomNavigationBar;

    private ArrayList<Fragment> fragments;
    public String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
    private static final int PERMISSION_REQUEST_LOCATION = 1;

    private long firstTime = 0;
    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;
    private ImageView imageView;

    @Override
    protected void initViews() {
        bottomNavigationBar = findViewById(R.id.bottom_navigation_bar);
        bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        bottomNavigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);
        if (BaseApplication.isAudit == 0) {
            bottomNavigationBar
                    .addItem(new BottomNavigationItem(R.mipmap.myturn, "首页").setActiveColor(ContextCompat.getColor(mContext, R.color.mainGreen)))
                    .addItem(new BottomNavigationItem(R.mipmap.im, "我的患者").setActiveColor(ContextCompat.getColor(mContext, R.color.mainGreen)))
                    .addItem(new BottomNavigationItem(R.mipmap.mine, "个人中心").setActiveColor(ContextCompat.getColor(mContext, R.color.mainGreen)))
                    .setFirstSelectedPosition(0)
                    .initialise();
        } else if (BaseApplication.isAudit == 2) {
            bottomNavigationBar
                    .addItem(new BottomNavigationItem(R.mipmap.icon_nurse_home, "首页").setActiveColor(ContextCompat.getColor(mContext, R.color.mainGreen)))
                    .addItem(new BottomNavigationItem(R.mipmap.mine, "个人中心").setActiveColor(ContextCompat.getColor(mContext, R.color.mainGreen)))
                    .setFirstSelectedPosition(0)
                    .initialise();
        } else {
            bottomNavigationBar
                    .addItem(new BottomNavigationItem(R.mipmap.zaixian, "处方审核").setActiveColor("#209187"))
                    .addItem(new BottomNavigationItem(R.mipmap.mine, "个人中心").setActiveColor("#209187"))
                    .setFirstSelectedPosition(0)
                    .initialise();
        }
        fragments = getFragments();
        setDefaultFragment();
        bottomNavigationBar.setTabSelectedListener(this);
        setBottomNavigationItem(bottomNavigationBar);
        if (BaseApplication.isAudit == 0) {
            checkPermissionAndShow();
        }
    }


    @Override
    protected void initData() {
        getUserInfo();
        EventBus.getDefault().register(this);
//        checkPermission();
        stopService(new Intent(MainActivity.this, WebSocketService.class));
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(this, WebSocketService.class));
        } else {
            startService(new Intent(this, WebSocketService.class));
        }
//        updateUmengDevice();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.aty_main;
    }

    private ArrayList<Fragment> getFragments() {
        ArrayList<Fragment> fragments = new ArrayList<>();
//        fragments.add(MyRegistrationFragment.newInstance());
        if (BaseApplication.isAudit == 0) {
            fragments.add(HomeFragment.newInstance());
            fragments.add(ContactsFragment.newInstance());
            fragments.add(MineFragment.newInstance());
        } else if (BaseApplication.isAudit == 2) {
            fragments.add(HomeNurseFragment.newInstance());
            fragments.add(MineFragment.newInstance());
        } else {
//            fragments.add(IMFragment.newInstance());
            fragments.add(PrescriptionFragment.newInstance());
            fragments.add(MineFragment.newInstance());
        }
        return fragments;
    }

    private void setDefaultFragment() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        if (BaseApplication.isAudit == 0) {
            transaction.replace(R.id.layFrame, HomeFragment.newInstance());
            ImmersionBar.with(this).keyboardEnable(true).statusBarColor(R.color.mainGreen).navigationBarColor(R.color.black).autoDarkModeEnable(true).init();
        } else if (BaseApplication.isAudit == 2) {
            transaction.replace(R.id.layFrame, HomeNurseFragment.newInstance());
        } else {
            transaction.replace(R.id.layFrame, PrescriptionFragment.newInstance());
        }
        transaction.commit();
    }

    @Override
    public void onTabSelected(int position) {
        if (fragments != null) {
            if (position < fragments.size()) {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                Fragment fragment = fragments.get(position);
                if (fragment.isAdded()) {
                    ft.replace(R.id.layFrame, fragment);
                } else {
                    ft.add(R.id.layFrame, fragment);
                }
                ft.commitAllowingStateLoss();
            }
        }
        if (BaseApplication.isAudit == 0) {
            if (position == 0) {
                ImmersionBar.with(this).keyboardEnable(true).statusBarColor(R.color.mainGreen).fitsSystemWindows(true).navigationBarColor(R.color.black).autoDarkModeEnable(true).init();
            } else if (position == 2) {
                ImmersionBar.with(this).keyboardEnable(true).statusBarColor(R.color.fff8f8f8).fitsSystemWindows(true).navigationBarColor(R.color.black).autoDarkModeEnable(true).init();
            } else {
                ImmersionBar.with(this).keyboardEnable(true).statusBarColor(R.color.white).fitsSystemWindows(true).navigationBarColor(R.color.black).autoDarkModeEnable(true).init();
            }
        } else if (BaseApplication.isAudit == 2) {
            if (position == 1) {
                ImmersionBar.with(this).keyboardEnable(true).statusBarColor(R.color.fff8f8f8).fitsSystemWindows(true).navigationBarColor(R.color.black).autoDarkModeEnable(true).init();
            } else {
                ImmersionBar.with(this).keyboardEnable(true).statusBarColor(R.color.white).fitsSystemWindows(true).navigationBarColor(R.color.black).autoDarkModeEnable(true).init();
            }
        } else {
            if (position == 0) {
                ImmersionBar.with(this).keyboardEnable(true).statusBarColor(R.color.white).fitsSystemWindows(true).navigationBarColor(R.color.black).autoDarkModeEnable(true).init();
            } else {
                ImmersionBar.with(this).keyboardEnable(true).statusBarColor(R.color.fff8f8f8).fitsSystemWindows(true).navigationBarColor(R.color.black).autoDarkModeEnable(true).init();
            }
        }
    }

    @Override
    public void onTabUnselected(int position) {

        if (fragments != null) {
            if (position < fragments.size()) {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                Fragment fragment = fragments.get(position);
                ft.remove(fragment);
                ft.commitAllowingStateLoss();
            }
        }
    }

    @Override
    public void onTabReselected(int position) {

    }


    @Subscribe
    public void onMessageEvent(Logout event) {
        switch (event.logout) {
            case 1:
            case 3:
                HomeFragment.Logout();
                ContactsFragment.Logout();
                MineFragment.Logout();
                PrescriptionFragment.Logout();
                finish();
            case 6:
                if (imageView != null) {
                    windowManager.removeView(imageView);
                }
                break;
            default:
                break;
        }
    }

    private void setBottomNavigationItem(BottomNavigationBar bottomNavigationBar) {
        Class barClass = bottomNavigationBar.getClass();
        Field[] fields = barClass.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            if (field.getName().equals("mTabContainer")) {
                try {
                    //反射得到 mTabContainer
                    LinearLayout mTabContainer = (LinearLayout) field.get(bottomNavigationBar);
                    for (int j = 0; j < mTabContainer.getChildCount(); j++) {
                        //获取到容器内的各个Tab
                        View view = mTabContainer.getChildAt(j);
                        //获取到Tab内的各个显示控件
                        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dip2px(56));
                        FrameLayout container = (FrameLayout) view.findViewById(R.id.fixed_bottom_navigation_container);
                        container.setLayoutParams(params);
                        container.setPadding(dip2px(12), dip2px(0), dip2px(12), dip2px(0));

                        //获取到Tab内的文字控件
                        TextView labelView = (TextView) view.findViewById(com.ashokvarma.bottomnavigation.R.id.fixed_bottom_navigation_title);
                        //计算文字的高度DP值并设置，setTextSize为设置文字正方形的对角线长度，所以：文字高度（总内容高度减去间距和图片高度）*根号2即为对角线长度，此处用DP值，设置该值即可。
                        labelView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
                        labelView.setIncludeFontPadding(false);
                        labelView.setPadding(0, 0, 0, dip2px(20 - 10));

                        //获取到Tab内的图像控件
                        ImageView iconView = (ImageView) view.findViewById(com.ashokvarma.bottomnavigation.R.id.fixed_bottom_navigation_icon);
                        //设置图片参数，其中，MethodUtils.dip2px()：换算dp值
                        params = new FrameLayout.LayoutParams(dip2px(20), dip2px(20));
                        params.setMargins(0, 0, 0, 0 / 2);
                        params.gravity = Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL;
                        iconView.setLayoutParams(params);
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public int dip2px(float dpValue) {
        final float scale = getApplication().getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }


    protected void checkPermissionAndShow() {
        // 检查是否已经授权
        if (!FloatWinPermissionCompat.getInstance().check(this)) {
            // 授权提示
            new AlertDialog.Builder(this).setTitle("悬浮窗权限未开启")
                    .setMessage("你的手机没有授权" + this.getString(R.string.app_name) + "获得悬浮窗权限，视频悬浮窗功能将无法正常使用")
                    .setPositiveButton("开启", (dialog, which) -> {
                        // 显示授权界面
                        try {
                            FloatWinPermissionCompat.getInstance().apply(mContext);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    })
                    .setNegativeButton("取消", null).show();
        }
    }


    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 1000) {
                ToastUtil.showToast(mContext, "再按一次退出程序");
                firstTime = secondTime;
                return true;
            } else {
                stopService(new Intent(this, WebSocketService.class));
                System.exit(0);
            }
        }
        return super.onKeyUp(keyCode, event);
    }


    private void checkPermissions() {
        boolean agreeCamera = PreferencesHelper.getInstance().getBoolean(mContext, "agreeLocation");
        if (!agreeCamera) {
            ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("7", true);
            applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
            applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

                @Override
                public void onConfirm() {
                    ActivityCompat.requestPermissions(mContext, permissions, PERMISSION_REQUEST_LOCATION);
                }

                @Override
                public void onCancel() {

                }
            });

        } else {
            showFloatingWindow();
        }
    }

    private void showAddCallPersonDialog() {
        LocationUtils.AddressCallback addressCallback = LocationUtils.getInstance(mContext).getAddressCallback();
        LocationUtils.getInstance(mContext).removeAddressCallback(addressCallback);
        LocationUtils.getInstance(mContext).setAddressCallback(new LocationUtils.AddressCallback() {
            @Override
            public void onGetAddress(Address address) {
                String countryName = address.getCountryName();//国家
                String adminArea = address.getAdminArea();//省
                String locality = address.getLocality();//市
                String subLocality = address.getSubLocality();//区
                String featureName = address.getFeatureName();//具体地址
                String subAdminArea = address.getSubAdminArea();//街道
                String area = adminArea + locality + subLocality + subAdminArea + featureName;
                LogUtil.e("定位地址--", area);

            }

            @Override
            public void onGetLocation(double lat, double lng) {
                LogUtil.e("定位经纬度", lat + "维度" + lng);
            }
        });

    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NotNull String[] permissions, @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode != PERMISSION_REQUEST_LOCATION) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        } else {
            LogUtil.e("权限回调--" + Arrays.toString(permissions));
            PreferencesHelper.getInstance().set(mContext, "agreeLocation", true);
            showFloatingWindow();
            showAddCallPersonDialog();
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
//                // Permission Granted 授予权限
//                //处理授权之后逻辑
//
//
//            } else {
//                // Permission Denied 权限被拒绝
//                ToastUtil.showToast( mContext, "请同意相册和存储权限，否则功能无法使用" );
//                startNotificationSetting(mContext);
//            }

        }
    }

    @SuppressLint({"ClickableViewAccessibility", "RtlHardcoded"})
    private void showFloatingWindow() {
        if (imageView != null) {

            windowManager.removeView(imageView);
        }
        imageView = new ImageView(mContext);
//        imageView.setImageBitmap(null);
//        imageView.destroyDrawingCache();
        imageView.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_police));
        imageView.setOnTouchListener(new FloatingOnTouchListener());
        imageView.setOnClickListener(view -> {
            showAddCallPersonDialog();
            LogUtil.e("带你带那点");
        });

        layoutParams = new WindowManager
                .LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, 0, 0, PixelFormat.TRANSPARENT);
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }

        layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        layoutParams.x = 300;
        layoutParams.y = 300;
        windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(imageView, layoutParams);
    }

    private class FloatingOnTouchListener implements View.OnTouchListener {
        private int startX;
        private int startY;

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    startX = (int) event.getRawX();
                    startY = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int nowX = (int) event.getRawX();
                    int nowY = (int) event.getRawY();
                    int movedX = nowX - startX;
                    int movedY = nowY - startY;
                    startX = nowX;
                    startY = nowY;
                    layoutParams.x = layoutParams.x + movedX;
                    layoutParams.y = layoutParams.y + movedY;

                    // 更新悬浮窗控件布局
                    windowManager.updateViewLayout(view, layoutParams);
                    break;
                default:
                    break;
            }
            return false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }


    /**
     * 获取医生个人信息
     *
     * @time 2020/12/10 16:57
     */
    private void getUserInfo() {
        RestProxy.getInstance().getUserInfo(new Observer<DocInfoVO>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(DocInfoVO DocInfo) {
                try {
                    BaseApplication.doctorId = DocInfo.data.docId;
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void updateUmengDevice() {
        String uMengToken = PreferencesHelper.getInstance().getString(this, "uMengToken");
        LogUtil.e("uMengToken-----------", uMengToken);
        if (!UtilString.isEmpty(uMengToken)) {
            RestProxy.getInstance().updateUmengDevice(uMengToken, "0", new Observer<BaseResponse>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(BaseResponse baseResponse) {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (BaseApplication.isAudit == 2) {
            LocationUtils.AddressCallback addressCallback = LocationUtils.getInstance(mContext).getAddressCallback();
            LocationUtils.getInstance(mContext).removeAddressCallback(addressCallback);
        }
        super.onDestroy();
    }
}
